package com.mercenary.wein.screenControl.command.jobSchedual;

import com.android.ddmlib.NullOutputReceiver;
import com.mercenary.wein.screenControl.bean.CommandBean;
import com.mercenary.wein.screenControl.command.CommandSocketClient;
import com.mercenary.wein.screenControl.deviceControll.AndroidDevice;
import com.mercenary.wein.screenControl.service.CommandService;
import com.mercenary.wein.screenControl.ui.MainFrame;
import com.mercenary.wein.screenControl.ui.util.Constants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.io.*;
import java.util.Date;
import java.util.Random;

/**
 * Created by tuxiao on 2017/3/25.
 */
public class TaskJob implements Job {

    private static CommandService commandService = new CommandService();
    Log log = LogFactory.getLog(TaskJob.class);

    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDataMap dataMap = jobExecutionContext.getMergedJobDataMap();
        CommandBean commandBean = (CommandBean) dataMap.get("commandBean");
        //机器如果不在线就不用执行了
        if(!MainFrame.dcdMap.containsKey(commandBean.getSerialNo()))return;
        while (true) {
            long[] result = commandService.isRunning(commandBean.getSerialNo());
            Random random = new Random();
            if (result[0] == 0) {//没有正在执行的任务
                break;
            } else if (new Date().getTime() - result[1] > 1000 * 60 * 2) {//有正在执行的任务则将该任务状态改成失败
                commandService.shutdownTask(result[0]);
                break;
            }
            try {
                Thread.sleep(random.nextInt(2000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        final long id = commandService.insertTask(commandBean);
        //开始执行任务
        //1.看是否有文件需要传输
        if(commandBean.getFilePaths()!=null&&commandBean.getFilePaths().length()>0){
            AndroidDevice androidDevice = MainFrame.dcdMap.get(commandBean.getSerialNo()).getAndroidDevice();
            if(androidDevice!=null){
                for(String filePath:commandBean.getFilePaths().split("\\|")){
                    try{
                        File file = new File(filePath);
                        String fileName = System.currentTimeMillis()+"-"+file.getName();
                        androidDevice.pushFile(file, Constants.DeviceFilePath+fileName);
                        androidDevice.executeShellCommand("am broadcast -a android.intent.action.MEDIA_SCANNER_SCAN_FILE -d file://"+Constants.DeviceFilePath+fileName,new NullOutputReceiver());
                    }catch (Exception e){
                        log.info("文件传输错误，请检查文件是否存在！");
                        commandService.shutdownTask(id);
                    }
                }

            }
        }
        //2.建立socket发送命令
        try {
            CommandSocketClient csc = new CommandSocketClient("127.0.0.1", commandBean.getPort());
            String res = csc.command(commandBean.getContent());
            if (res.equals("2003")) {
                commandService.updateTask(id, 1);
            } else if (res.equals("2001")) {//需要打开辅助功能
                commandService.shutdownTask(id);
                if(MainFrame.dcdMap.containsKey(commandBean.getSerialNo())){
                    AndroidDevice androidDevice = MainFrame.dcdMap.get(commandBean.getSerialNo()).getAndroidDevice();
                    androidDevice.executeShellCommand("uiautomator dump "+ Constants.DeviceFilePath + "dump.xml",new NullOutputReceiver());
                    androidDevice.pullFile(Constants.DeviceFilePath + "dump.xml",Constants.LocalTempFilePath+"dump.xml");
                    int[] pixel = getCenterPixel(Constants.LocalTempFilePath+"dump.xml");
                    androidDevice.executeShellCommand("int tap "+pixel[0]+" "+pixel[1],new NullOutputReceiver());
                }
            } else {
                commandService.updateTask(id, 1);
            }
            csc.close();
        } catch (Exception e) {
            e.printStackTrace();
            MainFrame.dcdMap.get(commandBean.getSerialNo()).getAndroidDevice().createForward(commandBean.getPort(),3321);
            log.info("===============================执行命令出现异常=================================");
            commandService.shutdownTask(id);
        }
    }


    private int[] getCenterPixel(String filePath) throws IOException, DocumentException {
        InputStream inputStream = new FileInputStream(filePath);
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(inputStream);
        Element rootElement = document.getRootElement();
        String bounds = "";
        for(Object element : rootElement.selectNodes("//node")){
            if(!((Element)element).attribute("text").getValue().equals("微控终端"))continue;
            bounds = ((Element)element).attribute("bounds").getValue();
        }
        String[] xys = bounds.replace("][",",").replace("[","").replace("]","").split(",");
        int[] pixel = new int[2];
        pixel[0] = (Integer.parseInt(xys[0])+Integer.parseInt(xys[2]))/2;
        pixel[1] = (Integer.parseInt(xys[1])+Integer.parseInt(xys[3]))/2;
        inputStream.close();
        return pixel;
    }
}
